<template>
    <div class="post-detail-container">
        <div class="post-header">
            <h1>{{ post.title }}</h1>
            <div class="post-meta">
                <span>作者: {{ post.userName }}</span>
                <span>发布时间: {{ formatDate(post.createTime) }}</span>
                <span>阅读: {{ post.viewCount }}</span>
            </div>
        </div>

        <div class="post-content">
            <div v-html="post.content"></div>
        </div>

        <div class="post-actions">
            <button @click="toggleLike(post.id, post.isLiked)">{{ post.isLiked ? '取消点赞' : '点赞' }} ({{ post.likeCount
                }})</button>
            <button @click="toggleFavorite(post.id, post.isFavorited)">{{ post.isFavorited ? '取消收藏' : '收藏' }}</button>
            <button v-if="isAuthor" @click="editPost">编辑</button>
            <button v-if="isAuthor" @click="deletePost">删除</button>
        </div>

        <div class="reply-section">
            <h3>回复列表 ({{ replies.total }})</h3>
            <div class="reply-form">
                <textarea v-model="replyContent" placeholder="写下你的回复..."></textarea>
                <button @click="submitReply">提交回复</button>
            </div>
            <ul class="reply-list">
                <li v-for="reply in replies.items" :key="reply.id">
                    <div class="reply-user">
                        <span>{{ reply.userName }}</span>
                        <span>{{ formatDate(reply.createTime) }}</span>
                    </div>
                    <div class="reply-content">{{ reply.content }}</div>
                    <div class="reply-actions">
                        <button @click="toggleReplyLike(reply.id, reply.isLiked)">{{ reply.isLiked ? '取消点赞' : '点赞' }}
                            ({{ reply.likeCount }})</button>
                        <button @click="replyToReply(reply.id)">回复</button>
                    </div>
                    <!-- 回复的回复 -->
                    <div class="sub-reply-list" v-if="reply.subReplies && reply.subReplies.length > 0">
                        <ul>
                            <li v-for="subReply in reply.subReplies" :key="subReply.id">
                                <div class="reply-user">
                                    <span>{{ subReply.userName }}</span> 回复 <span>{{ subReply.targetUserName }}</span>
                                    <span>{{ formatDate(subReply.createTime) }}</span>
                                </div>
                                <div class="reply-content">{{ subReply.content }}</div>
                                <div class="reply-actions">
                                    <button @click="toggleReplyLike(subReply.id, subReply.isLiked)">{{ subReply.isLiked
                                        ? '取消点赞' : '点赞' }} ({{ subReply.likeCount }})</button>
                                    <button @click="replyToReply(subReply.id, subReply.userId)">回复</button>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <!-- 回复表单 -->
                    <div class="sub-reply-form" v-if="replyingTo === reply.id">
                        <textarea v-model="subReplyContent" placeholder="写下你的回复..."></textarea>
                        <button @click="submitSubReply(reply.id)">提交回复</button>
                        <button @click="cancelReply">取消</button>
                    </div>
                </li>
            </ul>
            <div class="pagination" v-if="replies.total > replies.pageSize">
                <button @click="changeReplyPage(1)" :disabled="replies.currentPage === 1">首页</button>
                <button @click="changeReplyPage(replies.currentPage - 1)"
                    :disabled="replies.currentPage === 1">上一页</button>
                <span>{{ replies.currentPage }}/{{ replies.totalPages }}</span>
                <button @click="changeReplyPage(replies.currentPage + 1)"
                    :disabled="replies.currentPage === replies.totalPages">下一页</button>
                <button @click="changeReplyPage(replies.totalPages)"
                    :disabled="replies.currentPage === replies.totalPages">末页</button>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
    getForumPostDetail,
    likePost,
    favoritePost,
    getPostReplies,
    createReply,
    likeReply,
    deleteForumPost
} from '@/api/forumApi'
// 删除错误的导入：import { useUserStore } from '@/stores/user'

// 添加获取用户信息的辅助函数
const getUserInfo = () => {
    try {
        const user = localStorage.getItem('user')
        return user ? JSON.parse(user) : null
    } catch (error) {
        console.error('解析用户信息失败:', error)
        return null
    }
}

export default {
    name: 'PostDetail',
    setup() {
        const router = useRouter()
        const route = useRoute()
        // 删除：const userStore = useUserStore()
        const postId = ref(route.params.id)
        const post = ref({})
        const replies = ref({
            items: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            totalPages: 1
        })
        const replyContent = ref('')
        const subReplyContent = ref('')
        const replyingTo = ref(null)
        const targetUserId = ref(null)
        const loading = ref(false)

        // 获取帖子详情
        const fetchPostDetail = async () => {
            loading.value = true
            try {
                const res = await getForumPostDetail(postId.value)
                post.value = res.data
            } catch (error) {
                console.error('获取帖子详情失败:', error)
            } finally {
                loading.value = false
            }
        }

        // 获取回复列表
        const fetchReplies = async () => {
            try {
                const res = await getPostReplies(postId.value, {
                    page: replies.value.currentPage,
                    limit: replies.value.pageSize
                })
                replies.value.items = res.data.items
                replies.value.total = res.data.total
                replies.value.totalPages = Math.ceil(res.data.total / replies.value.pageSize)
            } catch (error) {
                console.error('获取回复列表失败:', error)
            }
        }

        // 切换回复页码
        const changeReplyPage = (page) => {
            replies.value.currentPage = page
            fetchReplies()
        }

        // 点赞/取消点赞帖子
        const toggleLike = async (postId) => {
            try {
                await likePost(postId)
                post.value.isLiked = !post.value.isLiked
                post.value.likeCount = post.value.isLiked ? post.value.likeCount + 1 : post.value.likeCount - 1
            } catch (error) {
                console.error('点赞帖子失败:', error)
            }
        }

        // 收藏/取消收藏帖子
        const toggleFavorite = async (postId) => {
            try {
                await favoritePost(postId)
                post.value.isFavorited = !post.value.isFavorited
            } catch (error) {
                console.error('收藏帖子失败:', error)
            }
        }

        // 点赞/取消点赞回复
        const toggleReplyLike = async (replyId) => {
            try {
                await likeReply(replyId)
                // 更新本地状态
                const updateReplyLike = (replies) => {
                    return replies.map(reply => {
                        if (reply.id === replyId) {
                            return {
                                ...reply,
                                isLiked: !reply.isLiked,
                                likeCount: reply.isLiked ? reply.likeCount - 1 : reply.likeCount + 1
                            }
                        }
                        if (reply.subReplies && reply.subReplies.length > 0) {
                            return {
                                ...reply,
                                subReplies: updateReplyLike(reply.subReplies)
                            }
                        }
                        return reply
                    })
                }
                replies.value.items = updateReplyLike(replies.value.items)
            } catch (error) {
                console.error('点赞回复失败:', error)
            }
        }

        // 提交回复
        const submitReply = async () => {
            if (!replyContent.value.trim()) {
                alert('回复内容不能为空')
                return
            }

            try {
                await createReply(postId.value, {
                    content: replyContent.value
                })
                replyContent.value = ''
                fetchReplies()
            } catch (error) {
                console.error('提交回复失败:', error)
            }
        }

        // 提交子回复
        const submitSubReply = async (parentId) => {
            if (!subReplyContent.value.trim()) {
                alert('回复内容不能为空')
                return
            }

            try {
                await createReply(postId.value, {
                    content: subReplyContent.value,
                    parentId
                })
                subReplyContent.value = ''
                replyingTo.value = null
                targetUserId.value = null
                fetchReplies()
            } catch (error) {
                console.error('提交子回复失败:', error)
            }
        }

        // 回复某人
        const replyToReply = (replyId, userId = null) => {
            replyingTo.value = replyId
            targetUserId.value = userId
            // 滚动到回复框
            setTimeout(() => {
                const el = document.querySelector('.sub-reply-form textarea')
                if (el) el.focus()
            }, 100)
        }

        // 取消回复
        const cancelReply = () => {
            replyingTo.value = null
            targetUserId.value = null
            subReplyContent.value = ''
        }

        // 编辑回复
        // 删除 updateReply 函数

        // 删除回复
        // 删除 deleteReply 函数

        // 编辑帖子
        const editPost = () => {
            router.push({ name: 'EditPost', params: { id: postId.value } })
        }

        // 删除帖子
        const deletePost = async () => {
            if (confirm('确定要删除这篇帖子吗？')) {
                try {
                    await deleteForumPost(postId.value)
                    router.push({ name: 'ForumIndex' })
                } catch (error) {
                    console.error('删除帖子失败:', error)
                }
            }
        }

        // 格式化日期
        const formatDate = (dateString) => {
            const date = new Date(dateString)
            return date.toLocaleString()
        }

        // 是否为作者
        const isAuthor = computed(() => {
            const user = getUserInfo()
            return user && user.id === post.value.userId
        })

        // 修改 isReplyAuthor 函数
        const isReplyAuthor = (userId) => {
            const user = getUserInfo()
            return user && user.id === userId
        }

        // 删除 isLiked 和 isFavorited 变量

        // 删除重复的 isReplyAuthor 函数定义
        // const isReplyAuthor = (userId) => {
        //     return userStore.userInfo.id === userId
        // }

        // 初始化
        onMounted(() => {
            fetchPostDetail()
            fetchReplies()
        })

        return {
            post,
            replies,
            replyContent,
            subReplyContent,
            replyingTo,
            targetUserId,
            loading,
            fetchPostDetail,
            fetchReplies,
            changeReplyPage,
            toggleLike,
            toggleFavorite,
            submitReply,
            submitSubReply,
            replyToReply,
            cancelReply,
            toggleReplyLike,
            // 删除 editReply 和 deleteReply 引用
            editPost,
            deletePost,
            formatDate,
            isAuthor,
            isReplyAuthor
        }
    }
}
</script>

<style scoped>
/* 样式省略，可以根据实际需求添加 */
</style>